package com.blueberry.commbank.repository.impl;

import com.blueberry.commbank.domain.entity.Account;
import com.blueberry.commbank.domain.entity.Money;
import com.blueberry.commbank.persistence.AccountDO;
import com.blueberry.commbank.persistence.mapper.AccountMapper;
import com.blueberry.commbank.repository.AccountRepository;
import java.util.Currency;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class AccountRepositoryImpl implements AccountRepository {
    @Autowired
    private AccountMapper accountDAO;

    @Override
    public Account find(String accountNumber) {
        AccountDO accountDO = accountDAO.selectByAccountNumber(accountNumber);
        Account account = new Account();
        account.setId(accountDO.getId());
        account.setAccountId(accountDO.getAccountId());
        account.setAccountNumber(accountDO.getAccountNumber());
        account.setPinNumber(accountDO.getPinNumber());
        account.setBalance(new Money(accountDO.getBalance(),
                Currency.getInstance(accountDO.getCurrencyCode())));
        account.setDailyLimit(new Money(accountDO.getDailyLimit(),
                Currency.getInstance(accountDO.getCurrencyCode())));
        return account;
    }

    @Override
    public Account save(Account account) {
        AccountDO accountDO = AccountDO.valueOf(account);
        if (Objects.isNull(accountDO.getId())) {
            accountDAO.insert(accountDO);
        } else {
            accountDAO.update(accountDO);
        }
        accountDO = accountDAO.selectByAccountId(account.getAccountId());
        return AccountDO.toAccount(accountDO);
    }
}
